package com.seednia.foundation.framework.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class BeanUtils {

	public static void populateByCloning(Object bean, Map<String, Object> properties) 
		throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException 
	{
		// Do nothing unless both arguments have been specified
		if ((bean == null) || (properties == null)) {
		    return;
		}

		// Loop through the property name/value pairs to be set
		for (Map.Entry<String, Object> mapEntry:  properties.entrySet()) {
		    // Identify the property name and value(s) to be assigned
		    String name = mapEntry.getKey();
		    if (name == null) {
		        continue;
		    }

		    // Perform the assignment for this property
		    if (mapEntry.getValue() instanceof Cloneable) {
		    	Method  cloneMethod = mapEntry.getValue().getClass().getMethod("clone", null);
		    	Object cloned = cloneMethod.invoke(mapEntry.getValue());
		    	org.apache.commons.beanutils.BeanUtils.setProperty(bean, name, cloned);
		    } else {
		    	org.apache.commons.beanutils.BeanUtils.setProperty(bean, name, mapEntry.getValue());
		    }

		}
	}
}
